package aaaaa;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 限流
 */
public class MyGuavaRateLimiter {

    public static void main(String[] args) {

        //限流器流速：2个请求/秒
        RateLimiter limiter = RateLimiter.create(2);
        //执行任务的线程池
        ExecutorService es = Executors.newFixedThreadPool(5);
        //记录上一次执行时间
        AtomicLong prev = new AtomicLong(System.currentTimeMillis());
        //测试执行20次
        for (int i=0; i<20; i++){
            //限流器限流
            double limit =  limiter.acquire();
            System.out.println(limit);
            //提交任务异步执行
            es.execute(()->{
                long cur=System.currentTimeMillis();
                //打印时间间隔：毫秒
                System.out.println(cur/1000);
                prev.set(cur);
            });
        }


    }
}
